package com.xuanyuanxinyu.core.base

import android.app.Application
import android.content.Context
import android.os.Build
import android.text.TextUtils
import android.webkit.WebView
import androidx.multidex.MultiDex
import com.alibaba.android.arouter.launcher.ARouter
import com.xuanyuanxinyu.core.listener.AppActivityLifecycleCallbacks
import com.xuanyuanxinyu.core.listener.LifecycleListener
import com.xuanyuanxinyu.core.listener.SimpleAppLifecycleCallback
import com.xuanyuanxinyu.core.utils.LogUtils
import java.util.UUID


class RootApplication : Application() {
    override fun attachBaseContext(base : Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }
    
    override fun onCreate() {
        super.onCreate()
        if (AppConfig.isDebugMode()) {
            //打印日志
            ARouter.openLog()
            //开启调试模式(如果在InstantRun的模式下必须开启，线上必须关闭)
            ARouter.openDebug()
        }
        // 官方建议在Application中初始化
        ARouter.init(this)
        
        ApplicationUtils.initContext(this)
        ContextUtil.init(this)
        registerLifecycleCallbacks()
    }
    
    /**
     * 安卓9 10 多进程 webview 适配
     *
     */
    private fun setWebViewSuffix(progressName : String) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                WebView.setDataDirectorySuffix(if (TextUtils.isEmpty(progressName)) UUID.randomUUID().toString() else progressName)
            }
        } catch (e : Exception) {
            LogUtils.logError("WebView set data directory error =$e")
        }
    }
    
    /**
     * 注册生命周期监听
     */
    private fun registerLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(AppActivityLifecycleCallbacks())
        val lifecycleListener : LifecycleListener = LifecycleListener()
        lifecycleListener.addCallback(SimpleAppLifecycleCallback())
        //        ProcessLifecycleOwner  .get().lifecycle.addObserver(lifecycleListener)
    }
}